package com.mgface.eth.tool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
import org.web3j.protocol.core.methods.response.TransactionReceipt;

import java.util.Optional;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project eth
 * @create 2018-06-27 18:16
 **/
public class TxHashGetReceipt {
	private static final Logger log = LoggerFactory.getLogger(TxHashGetReceipt.class);
	private static final int ATTEMPTS = 40;
	private static final int SLEEP_DURATION = 15_000;
	/**
	 * 返回交易的收据
	 * @param transactionHash
	 * @return
	 */
	public static TransactionReceipt passTxHashGetReceipt(String transactionHash){
		try {
			Optional<TransactionReceipt> receipt = sendTxReceiptRequest(transactionHash);
			for (int i = 0; i < ATTEMPTS; i++) {
				if (!receipt.isPresent()){
					Thread.sleep(SLEEP_DURATION);
					receipt = sendTxReceiptRequest(transactionHash);
				}else{
					break;
				}
			}
			//判断是否存在这个值
			if (receipt.isPresent()) {
				return receipt.get();
			}else {
				log.error("Transaction receipt not generated after {} attempts",SLEEP_DURATION);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	private static Optional<TransactionReceipt> sendTxReceiptRequest(String transactionHash) throws Exception {
		EthGetTransactionReceipt transactionReceipt = Web3JInstance.getWeb3jInstance().ethGetTransactionReceipt(transactionHash).sendAsync().get();
		return transactionReceipt.getTransactionReceipt();
	}
}
